package com.bl.weilan.service.biz.main.impl;

import com.bl.weilan.common.ApiResponseCode;
import com.bl.weilan.common.CommonServiceException;
import com.bl.weilan.common.enums.UserStatus;
import com.bl.weilan.common.enums.WechatBusinessType;
import com.bl.weilan.common.utils.CommonUtils;
import com.bl.weilan.common.utils.Generator;
import com.bl.weilan.common.utils.UUIDUtils;
import com.bl.weilan.dao.model.EmployeeEntity;
import com.bl.weilan.dao.redis.MessageDao;
import com.bl.weilan.dao.redis.UserInfoDao;
import com.bl.weilan.dao.redis.model.UserInfo;
import com.bl.weilan.dao.repository.UserRepository;
import com.bl.weilan.service.biz.main.MainService;
import com.bl.weilan.service.biz.user.UserService;
import com.bl.weilan.service.vo.main.*;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * Created by liangweikang on 2018/1/18.
 */
@Log4j2
@Service
public class MainServiceImpl implements MainService {

    private final String REGISTER_DUPLICATED_PHONE = "该手机号码已被注册";
    private final String REGISTER_DUPLICATED_ACCOUNT = "该帐号已被注册";

    @Autowired
    MessageDao messageDao;

    @Autowired
    MainService mainService;

    @Autowired
    UserService userService;

    @Autowired
    UserRepository userRepository;

    @Autowired
    UserInfoDao userInfoDao;

    @Override
    public LoginResponseVo appLogin(LoginVo loginVo) {

        EmployeeEntity userEntity = fetchAvailableUser(loginVo.getMobile(), loginVo.getPassword());

        String token = Generator.generateToken(userEntity.getId(), userEntity.getMobile(), userEntity.getPassword());
        if (!verifyCaptcha(loginVo.getMobile(), loginVo.getCaptcha())) {
            throw new CommonServiceException(ApiResponseCode.CAPTCHA_WRONG.getCode(), ApiResponseCode.CAPTCHA_WRONG.getMsg());
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setId(userEntity.getId());
        userInfo.setMobile(userEntity.getMobile());
        userInfo.setToken(token);

        userInfoDao.setUserInfo(userInfo);

        LoginResponseVo loginResponseVo;
        loginResponseVo = LoginResponseVo.builder()
                .mobile(userEntity.getMobile())
                .name(userEntity.getName())
                .vip(userEntity.getVip())
                .token(token)
                .avatar(userEntity.getAvatar())
                .institution(userEntity.getInstitution())
                .city(userEntity.getCity())
                .createTime(userEntity.getCreateTime())
                .id(userEntity.getId())
                .contacter(userEntity.getContacter())
                .build();

        return loginResponseVo;
    }

    private EmployeeEntity fetchAvailableUser(String account, String password) {
        EmployeeEntity userEntity = userService.getUserByMobile(account);

        if (userEntity == null) {
            throw new CommonServiceException(ApiResponseCode.USER_NOT_EXIST.getCode(), ApiResponseCode.USER_NOT_EXIST.getMsg());
        }

        if (!userEntity.getPassword().equals(password)) {
            throw new CommonServiceException(ApiResponseCode.PASSWORD_WRONG.getCode(), ApiResponseCode.PASSWORD_WRONG.getMsg());
        }

        if (userEntity.getStatus() == UserStatus.LOCKED) {
            throw new CommonServiceException(ApiResponseCode.USER_LOCKED.getCode(), ApiResponseCode.USER_LOCKED.getMsg());
        }
        return userEntity;
    }


    @Override
    public void reset(ResetVo resetVo) {
        
        EmployeeEntity userEntity = userService.getUserByMobile(resetVo.getAccount());
        if (userEntity == null) {
            throw new CommonServiceException(ApiResponseCode.USER_NOT_EXIST.getCode(), ApiResponseCode.USER_NOT_EXIST.getMsg());
        }
        if (!resetVo.getOldPassword().equals(userEntity.getPassword())) {
            throw new CommonServiceException(ApiResponseCode.PASSWORD_WRONG.getCode(), ApiResponseCode.PASSWORD_WRONG.getMsg());
        }
        userEntity.setPassword(resetVo.getPassword());

        userRepository.save(userEntity);

    }

    @Override
    public void forget(ForgetVo forgetVo) {

        if (!verifyCaptcha(forgetVo.getMobile(), forgetVo.getCaptcha())) {
            throw new CommonServiceException(ApiResponseCode.CAPTCHA_WRONG.getCode(), ApiResponseCode.CAPTCHA_WRONG.getMsg());
        }
        EmployeeEntity userEntity = userService.getUserByMobile(forgetVo.getMobile());
        if (userEntity == null) {
            throw new CommonServiceException(ApiResponseCode.USER_NOT_EXIST.getCode(), ApiResponseCode.USER_NOT_EXIST.getMsg());
        }
        userEntity.setPassword(forgetVo.getPassword());
        userRepository.save(userEntity);

    }

    @Override
    public void logout(UserInfo userInfo) {
        userInfoDao.delUserInfo(userInfo.getMobile());
    }


    @Override
    @Transactional
    public LoginResponseVo register(RegisterVo registerVo) {

        if (userService.getUserByMobile(registerVo.getMobile()) != null) {
            throw new CommonServiceException(ApiResponseCode.DATA_EXISTED.getCode(), REGISTER_DUPLICATED_PHONE);
        }

        if (!verifyCaptcha(registerVo.getMobile(), registerVo.getCaptcha())) {
            throw new CommonServiceException(ApiResponseCode.CAPTCHA_WRONG.getCode(), ApiResponseCode.CAPTCHA_WRONG.getMsg());
        }

        EmployeeEntity employeeEntity = new EmployeeEntity();

        employeeEntity.setId(Generator.generateId());
        employeeEntity.setMobile(registerVo.getMobile());
        employeeEntity.setPassword(registerVo.getPassword());
        employeeEntity.setStatus(UserStatus.NORMAL);
        employeeEntity.setAvatar(registerVo.getAvatar());
        employeeEntity.setCity(registerVo.getCity());
        employeeEntity.setInstitution(registerVo.getInstitution());
        employeeEntity.setCreateTime(new Date());
        employeeEntity.setUpdateTime(new Date());
        userRepository.save(employeeEntity);

        LoginResponseVo loginResponseVo;
        loginResponseVo = LoginResponseVo.builder()
                .mobile(employeeEntity.getMobile())
                .name(employeeEntity.getName())
                .avatar(employeeEntity.getAvatar())
                .id(employeeEntity.getId())
                .city(employeeEntity.getCity())
                .institution(employeeEntity.getInstitution())
                .createTime(employeeEntity.getCreateTime())
                .contacter(employeeEntity.getContacter())
                .build();

        return loginResponseVo;
    }

    private boolean verifyCaptcha(String mobile, String captcha) {
        String code = messageDao.getAuthCode(mobile);
        if (code == null || !code.equals(captcha)) {
            return false;
        }
        return true;
    }
}
